/**
 * 现代化技能引擎
 * 采用可配置的技能效果系统，替代旧版SkManager的内联函数架构
 */

import { 
    ModernSkill, 
    SkillInstance, 
    SkillUseRequest, 
    SkillUseResult,
    SkillEffectContext,
    SkillEffectResult,
    ISkillEffectHandler,
    SkillEffectType,
    SkillEffectConfig
} from './SkillEffectTypes';
import { BattleParticipant } from '../../battle/types';
import { ServiceLogger } from '../../../../infrastructure/logging/UnifiedLogger';
import { BaseGameService } from '../../../../service/base/BaseGameService';
import { HealthCheckResult } from '../../../../service/base/IGameService';
import { SkillEffectRegistry } from './SkillEffectRegistry';
import { SkillConfigurationLoader } from './SkillConfigurationLoader';
import { SkillConditionEvaluator } from './SkillConditionEvaluator';

/**
 * 技能引擎配置
 */
interface SkillEngineConfig {
    /** 是否启用调试模式 */
    debugMode?: boolean;
    /** 最大并发技能执行数 */
    maxConcurrentSkillUse?: number;
    /** 是否启用技能升级 */
    enableSkillUpgrade?: boolean;
    /** 是否启用永久提升 */
    enablePermanentBoosts?: boolean;
    /** 技能配置文件路径 */
    configPath?: string;
}

/**
 * 现代化技能引擎
 * 解决旧版SkManager的内联函数问题，采用可配置的效果处理器架构
 */
export class ModernSkillEngine extends BaseGameService {
    readonly serviceName = 'ModernSkillEngine';
    readonly dependencies = ['SkillEffectRegistry', 'SkillConfigurationLoader'];

    private effectRegistry: SkillEffectRegistry;
    private configLoader: SkillConfigurationLoader;
    private conditionEvaluator: SkillConditionEvaluator;
    
    // 技能定义和实例管理
    private skillDefinitions = new Map<string, ModernSkill>();
    private skillInstances = new Map<string, Map<string, SkillInstance>>(); // playerId -> skillId -> instance
    
    // 引擎配置
    private engineConfig: SkillEngineConfig;
    
    // 性能统计
    private performanceStats = {
        totalSkillsUsed: 0,
        avgExecutionTime: 0,
        failureRate: 0,
        currentConcurrentUse: 0
    };

    constructor(container?: any, config?: SkillEngineConfig) {
        super(container);
        this.engineConfig = {
            debugMode: false,
            maxConcurrentSkillUse: 5,
            enableSkillUpgrade: true,
            enablePermanentBoosts: true,
            configPath: 'src/core/rpg/config/skills/',
            ...config
        };
    }

    /**
     * 服务初始化
     */
    protected async onInit(): Promise<void> {
        this.log('info', 'Initializing Modern Skill Engine...');
        
        try {
            // 初始化组件
            this.effectRegistry = new SkillEffectRegistry();
            this.configLoader = new SkillConfigurationLoader(this.engineConfig.configPath!);
            this.conditionEvaluator = new SkillConditionEvaluator();

            // 加载技能配置
            await this.loadSkillConfigurations();
            
            // 注册内置效果处理器
            await this.registerBuiltinEffectHandlers();
            
            this.log('info', 'Modern Skill Engine initialized successfully', {
                metadata: { 
                    skillCount: this.skillDefinitions.size,
                    effectHandlerCount: this.effectRegistry.getHandlerCount()
                }
            });
            
        } catch (error) {
            this.log('error', 'Failed to initialize Modern Skill Engine', undefined, error);
            throw error;
        }
    }

    /**
     * 服务销毁
     */
    protected async onDestroy(): Promise<void> {
        this.log('info', 'Destroying Modern Skill Engine...');
        
        // 清理缓存
        this.skillDefinitions.clear();
        this.skillInstances.clear();
        
        this.log('info', 'Modern Skill Engine destroyed');
    }

    /**
     * 健康检查
     */
    protected async onHealthCheck(): Promise<HealthCheckResult> {
        const isHealthy = this.performanceStats.currentConcurrentUse < this.engineConfig.maxConcurrentSkillUse!;
        
        return {
            healthy: isHealthy,
            message: isHealthy 
                ? 'Skill engine running normally' 
                : `Too many concurrent skill uses: ${this.performanceStats.currentConcurrentUse}`,
            timestamp: Date.now(),
            details: {
                skillDefinitions: this.skillDefinitions.size,
                activeInstances: this.getTotalActiveInstances(),
                performanceStats: this.performanceStats
            }
        };
    }

    // ==================== 公共API ====================

    /**
     * 使用技能
     */
    async useSkill(request: SkillUseRequest): Promise<SkillUseResult> {
        return this.recordCall('useSkill', async () => {
            // 检查并发限制
            if (this.performanceStats.currentConcurrentUse >= this.engineConfig.maxConcurrentSkillUse!) {
                return this.createFailureResult(request, 'Maximum concurrent skill uses reached');
            }

            this.performanceStats.currentConcurrentUse++;
            const startTime = Date.now();

            try {
                // 获取技能实例
                const skillInstance = this.getSkillInstance(request.casterId, request.skillId);
                if (!skillInstance) {
                    return this.createFailureResult(request, 'Skill not found or not learned');
                }

                // 验证使用条件
                const validationResult = await this.validateSkillUse(request, skillInstance);
                if (!validationResult.valid) {
                    return this.createFailureResult(request, validationResult.reason!);
                }

                // 执行技能
                const result = await this.executeSkill(request, skillInstance);

                // 更新统计
                this.updatePerformanceStats(startTime, true);

                return result;

            } catch (error) {
                this.log('error', `Skill use failed: ${request.skillId}`, undefined, error);
                this.updatePerformanceStats(startTime, false);
                return this.createFailureResult(request, `Execution error: ${(error as Error).message}`);
            } finally {
                this.performanceStats.currentConcurrentUse--;
            }
        });
    }

    /**
     * 学习技能
     */
    async learnSkill(playerId: string, skillId: string, initialLevel: number = 1): Promise<boolean> {
        return this.recordCall('learnSkill', async () => {
            const skillDefinition = this.skillDefinitions.get(skillId);
            if (!skillDefinition) {
                this.log('warn', `Skill definition not found: ${skillId}`);
                return false;
            }

            // 检查学习条件
            const canLearn = await this.checkLearningRequirements(playerId, skillDefinition);
            if (!canLearn) {
                this.log('info', `Learning requirements not met`, {
                    metadata: { playerId, skillId }
                });
                return false;
            }

            // 创建技能实例
            const skillInstance: SkillInstance = {
                baseSkill: skillDefinition,
                level: initialLevel,
                experience: 0,
                useCount: 0,
                currentCooldown: 0,
                currentCharges: skillDefinition.cooldown.maxCharges || undefined,
                permanentBoosts: new Map(),
                temporaryModifiers: [],
                customData: new Map()
            };

            // 存储实例
            if (!this.skillInstances.has(playerId)) {
                this.skillInstances.set(playerId, new Map());
            }
            this.skillInstances.get(playerId)!.set(skillId, skillInstance);

            this.log('info', `Skill learned successfully`, {
                metadata: { playerId, skillId, level: initialLevel }
            });

            return true;
        });
    }

    /**
     * 升级技能
     */
    async upgradeSkill(playerId: string, skillId: string, experienceGain: number): Promise<boolean> {
        return this.recordCall('upgradeSkill', async () => {
            if (!this.engineConfig.enableSkillUpgrade) {
                return false;
            }

            const skillInstance = this.getSkillInstance(playerId, skillId);
            if (!skillInstance) {
                return false;
            }

            const oldLevel = skillInstance.level;
            skillInstance.experience += experienceGain;

            // 检查是否可以升级
            const learningConfig = skillInstance.baseSkill.learning;
            if (!learningConfig) {
                return false;
            }

            const expNeeded = learningConfig.upgrade.expPerLevel[skillInstance.level - 1];
            if (skillInstance.experience >= expNeeded && skillInstance.level < learningConfig.upgrade.maxLevel) {
                skillInstance.level++;
                skillInstance.experience -= expNeeded;

                // 应用升级效果
                await this.applyLevelUpEffects(skillInstance);

                this.log('info', `Skill leveled up`, {
                    metadata: { 
                        playerId, 
                        skillId, 
                        oldLevel, 
                        newLevel: skillInstance.level,
                        experienceGain
                    }
                });

                return true;
            }

            return false;
        });
    }

    /**
     * 添加永久提升
     */
    async addPermanentBoost(
        playerId: string, 
        skillId: string, 
        boostType: string, 
        amount: number
    ): Promise<boolean> {
        return this.recordCall('addPermanentBoost', async () => {
            if (!this.engineConfig.enablePermanentBoosts) {
                return false;
            }

            const skillInstance = this.getSkillInstance(playerId, skillId);
            if (!skillInstance) {
                return false;
            }

            const currentBoost = skillInstance.permanentBoosts.get(boostType) || 0;
            skillInstance.permanentBoosts.set(boostType, currentBoost + amount);

            this.log('info', `Permanent boost added`, {
                metadata: { playerId, skillId, boostType, amount, newTotal: currentBoost + amount }
            });

            return true;
        });
    }

    /**
     * 获取玩家的所有技能
     */
    getPlayerSkills(playerId: string): SkillInstance[] {
        const playerSkills = this.skillInstances.get(playerId);
        return playerSkills ? Array.from(playerSkills.values()) : [];
    }

    /**
     * 获取技能定义
     */
    getSkillDefinition(skillId: string): ModernSkill | undefined {
        return this.skillDefinitions.get(skillId);
    }

    /**
     * 获取所有技能定义
     */
    getAllSkillDefinitions(): ModernSkill[] {
        return Array.from(this.skillDefinitions.values());
    }

    /**
     * 注册自定义效果处理器
     */
    registerEffectHandler(handler: ISkillEffectHandler): void {
        this.effectRegistry.registerHandler(handler);
        this.log('info', `Effect handler registered: ${handler.effectType}`);
    }

    /**
     * 获取性能统计
     */
    getPerformanceStats() {
        return { ...this.performanceStats };
    }

    // ==================== 私有方法 ====================

    /**
     * 加载技能配置
     */
    private async loadSkillConfigurations(): Promise<void> {
        try {
            const skillConfigs = await this.configLoader.loadAllSkills();
            
            for (const config of skillConfigs) {
                this.skillDefinitions.set(config.id, config);
            }

            this.log('info', `Loaded ${skillConfigs.length} skill definitions`);
        } catch (error) {
            this.log('error', 'Failed to load skill configurations', undefined, error);
            throw error;
        }
    }

    /**
     * 注册内置效果处理器
     */
    private async registerBuiltinEffectHandlers(): Promise<void> {
        // 动态导入所有内置处理器
        const handlerModules = [
            './handlers/DamageEffectHandler',
            './handlers/HealEffectHandler',
            './handlers/BuffEffectHandler',
            './handlers/AttributeEffectHandler',
            './handlers/SpecialEffectHandler'
        ];

        for (const modulePath of handlerModules) {
            try {
                const module = await import(modulePath);
                const HandlerClass = module.default || module[Object.keys(module)[0]];
                if (HandlerClass && typeof HandlerClass === 'function') {
                    const handler = new HandlerClass();
                    this.effectRegistry.registerHandler(handler);
                }
            } catch (error) {
                this.log('warn', `Failed to load handler: ${modulePath}`, undefined, error);
            }
        }
    }

    /**
     * 获取技能实例
     */
    private getSkillInstance(playerId: string, skillId: string): SkillInstance | undefined {
        const playerSkills = this.skillInstances.get(playerId);
        return playerSkills?.get(skillId);
    }

    /**
     * 验证技能使用条件
     */
    private async validateSkillUse(
        request: SkillUseRequest, 
        skillInstance: SkillInstance
    ): Promise<{ valid: boolean; reason?: string }> {
        // 检查冷却
        if (skillInstance.currentCooldown > 0 && !request.forceUse) {
            return { valid: false, reason: 'Skill is on cooldown' };
        }

        // 检查充能
        if (skillInstance.baseSkill.cooldown.maxCharges) {
            if ((skillInstance.currentCharges || 0) <= 0 && !request.forceUse) {
                return { valid: false, reason: 'No charges available' };
            }
        }

        // 检查目标数量
        const targetConfig = skillInstance.baseSkill.targeting;
        if (typeof targetConfig.targetCount === 'number') {
            if (request.targetIds.length !== targetConfig.targetCount) {
                return { valid: false, reason: 'Invalid target count' };
            }
        }

        return { valid: true };
    }

    /**
     * 执行技能
     */
    private async executeSkill(
        request: SkillUseRequest, 
        skillInstance: SkillInstance
    ): Promise<SkillUseResult> {
        const effects: SkillEffectResult[] = [];
        const actualTargetIds: string[] = [];

        // 创建技能效果上下文
        const context: SkillEffectContext = {
            skillId: request.skillId,
            caster: { id: request.casterId } as BattleParticipant, // 简化实现
            targets: request.targetIds.map(id => ({ id } as BattleParticipant)),
            skillData: this.buildSkillData(skillInstance),
            stackCount: 1,
            effectIndex: 0,
            params: request.params
        };

        // 执行所有技能效果
        for (let i = 0; i < skillInstance.baseSkill.effects.length; i++) {
            const effectConfig = skillInstance.baseSkill.effects[i];
            context.effectIndex = i;

            try {
                const effectResult = await this.executeEffect(context, effectConfig);
                effects.push(effectResult);
                
                // 收集受影响的目标
                actualTargetIds.push(...effectResult.affectedTargets);
            } catch (error) {
                this.log('error', `Effect execution failed`, undefined, error);
                effects.push({
                    success: false,
                    battleEffects: [],
                    affectedTargets: [],
                    description: `Effect failed: ${(error as Error).message}`
                });
            }
        }

        // 应用冷却和消耗
        this.applyCooldownAndConsumption(skillInstance);

        // 增加使用次数和经验
        skillInstance.useCount++;
        if (this.engineConfig.enableSkillUpgrade) {
            await this.upgradeSkill(request.casterId, request.skillId, 10);
        }

        return {
            success: true,
            skillId: request.skillId,
            casterId: request.casterId,
            actualTargetIds: [...new Set(actualTargetIds)],
            effects,
            resourceConsumed: skillInstance.baseSkill.resourceCost || { type: 'none', amount: 0 },
            cooldownSet: skillInstance.currentCooldown
        };
    }

    /**
     * 执行单个效果
     */
    private async executeEffect(
        context: SkillEffectContext, 
        config: SkillEffectConfig
    ): Promise<SkillEffectResult> {
        // 检查触发条件
        if (config.conditions) {
            const conditionsMet = await this.conditionEvaluator.evaluateConditions(
                config.conditions, 
                context
            );
            if (!conditionsMet) {
                return {
                    success: false,
                    battleEffects: [],
                    affectedTargets: [],
                    description: 'Conditions not met'
                };
            }
        }

        // 检查触发概率
        if (config.probability && Math.random() > config.probability) {
            return {
                success: false,
                battleEffects: [],
                affectedTargets: [],
                description: 'Probability check failed'
            };
        }

        // 获取效果处理器
        const handler = this.effectRegistry.getHandler(config.type);
        if (!handler) {
            throw new Error(`No handler found for effect type: ${config.type}`);
        }

        // 执行效果
        return await handler.execute(context, config);
    }

    /**
     * 构建技能数据
     */
    private buildSkillData(skillInstance: SkillInstance): any {
        const baseData = { level: skillInstance.level };
        
        // 应用永久提升
        for (const [boostType, amount] of skillInstance.permanentBoosts) {
            baseData[boostType] = (baseData[boostType] || 0) + amount;
        }

        return baseData;
    }

    /**
     * 应用冷却和消耗
     */
    private applyCooldownAndConsumption(skillInstance: SkillInstance): void {
        const cooldownConfig = skillInstance.baseSkill.cooldown;
        
        if (cooldownConfig.maxCharges) {
            // 充能系统
            skillInstance.currentCharges = (skillInstance.currentCharges || 0) - 1;
        } else {
            // 普通冷却
            skillInstance.currentCooldown = cooldownConfig.baseCooldown;
        }
    }

    /**
     * 检查学习条件
     */
    private async checkLearningRequirements(playerId: string, skill: ModernSkill): Promise<boolean> {
        if (!skill.learning?.requirements) {
            return true; // 无条件限制
        }

        const requirements = skill.learning.requirements;
        
        // 检查前置技能
        if (requirements.skills) {
            const playerSkills = this.skillInstances.get(playerId);
            for (const requiredSkill of requirements.skills) {
                if (!playerSkills?.has(requiredSkill)) {
                    return false;
                }
            }
        }

        // 其他条件检查...
        return true;
    }

    /**
     * 应用升级效果
     */
    private async applyLevelUpEffects(skillInstance: SkillInstance): Promise<void> {
        const learningConfig = skillInstance.baseSkill.learning;
        if (!learningConfig) return;

        // 检查是否有新效果需要解锁
        const newEffects = learningConfig.upgrade.newEffectsPerLevel?.[skillInstance.level];
        if (newEffects) {
            // 这里可以添加逻辑来动态添加新效果
            this.log('info', `New effects unlocked at level ${skillInstance.level}`, {
                metadata: { skillId: skillInstance.baseSkill.id, effectCount: newEffects.length }
            });
        }
    }

    /**
     * 创建失败结果
     */
    private createFailureResult(request: SkillUseRequest, reason: string): SkillUseResult {
        return {
            success: false,
            skillId: request.skillId,
            casterId: request.casterId,
            actualTargetIds: [],
            effects: [],
            resourceConsumed: { type: 'none', amount: 0 },
            cooldownSet: 0,
            failureReason: reason
        };
    }

    /**
     * 更新性能统计
     */
    private updatePerformanceStats(startTime: number, success: boolean): void {
        const duration = Date.now() - startTime;
        this.performanceStats.totalSkillsUsed++;
        
        // 更新平均执行时间
        this.performanceStats.avgExecutionTime = 
            (this.performanceStats.avgExecutionTime + duration) / 2;
        
        // 更新失败率
        if (!success) {
            this.performanceStats.failureRate = 
                (this.performanceStats.failureRate + 1) / this.performanceStats.totalSkillsUsed;
        }
    }

    /**
     * 获取总活跃实例数
     */
    private getTotalActiveInstances(): number {
        let total = 0;
        for (const playerSkills of this.skillInstances.values()) {
            total += playerSkills.size;
        }
        return total;
    }
}
